package com.ztools.wx.provider;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ztools.api.service.wx.WxConfigService;
import com.ztools.common.util.common.Result;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.menu.WxMpMenu;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

import static com.ztools.wx.config.WxSysConstants.WX_APP_ID;
import static com.ztools.wx.config.WxSysConstants.WX_SERVER_URL;

/**
 * @Author: seeTools
 * @Date: 2023/6/21  16:53
 * @Version 1.0
 */
@Service(version = "1.0", timeout = 3000)
public class WxConfigServiceImpl implements WxConfigService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private WxMpService wxMpService;


    @Override
    public String getWxServerUrl() {
        return WX_SERVER_URL;
    }

    @Override
    public String getWxServerAppId() {
        return WX_APP_ID;
    }

    @Override
    public Result getMenu() {
        try {
            WxMpMenu wxMpMenu = wxMpService.getMenuService().menuGet();
            return Result.success().data(wxMpMenu.getMenu());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return Result.error();
    }

    @Override
    public Result createMenuByJson(JSONObject params) {
        String json = params.getStr("json");
        logger.warn("json={}", json);
        if (!JSONUtil.isJson(json)) {
            return Result.error("菜单格式错误");
        }
        try {
            WxMenu menu = JSONUtil.toBean(json, WxMenu.class);
            logger.info("menu={}", menu);
            String isCreatedSuccess = wxMpService.getMenuService().menuCreate(menu);
            if (isCreatedSuccess == null) {
                return Result.success("创建成功");
            } else {
                return Result.error("发布失败");
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return Result.error();
    }
}
